import org.w3c.dom.Node;

import java.util.HashMap;

public class Offer35 {
    class Node {
        int val;
        Node next;
        Node random;

        public Node(int val) {
            this.val = val;
            this.next = null;
            this.random = null;
        }

    }

    public Node copyRandomList(Node head) {
        if (head == null) {
            return null;
        }
        Node pointer = head;
        Node myhead = new Node(head.val);
        Node statichead = myhead;
        HashMap<Node, Node> map = new HashMap<>();
        map.put(head, myhead);
        Node result = myhead;
        while (head != null&&head.next!=null) {
            Node mynext = new Node(head.next.val);
            myhead.next = mynext;
            head=head.next;
            map.put(head, mynext);
            myhead=myhead.next;
        }
        while (pointer!=null){
            statichead.random=map.get(pointer.random);
            statichead=statichead.next;
            pointer=pointer.next;
        }
        return result;
    }
    public Node copyRandomList1(Node head) {
        Node myhead = head;
        while (myhead!=null){
            Node pnode = new Node(myhead.val);
            pnode.next = myhead.next;
            myhead.next = pnode;
            myhead = pnode.next;
        }
        cloneSibling(head);
        return reconnectNodes(head);
    }

    public void cloneSibling(Node phead){
        Node pphead = phead;
        while (pphead!=null){
            Node clone = pphead.next;
            if (pphead.random!=null)
            clone.random = pphead.random.next;
            pphead = clone.next;
        }
    }
    public Node reconnectNodes(Node head){
        Node phead = head;
        Node cloneHead = null;
        Node cloneNode = null;
        if (phead!=null){
            cloneHead = cloneNode = phead.next;
            phead.next = cloneHead.next;
            phead=phead.next;
        }
        while (phead!=null){
            cloneNode.next = phead.next;
            cloneNode = cloneNode.next;
            phead.next = cloneNode.next;
            phead=phead.next;
        }
        return cloneHead;
    }
}
